package org.algorithm.biubiu.wheel_1.链表;


import org.algorithm.biubiu.wheel_1.common.ListNode;
import org.junit.Test;

/*****
 *
 *      周末的题：  周一要看，  没写的， 嘿嘿。。。   你们懂的
 *   参考uri: https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
 *
 */
public class K个一组反转链表 {


    @Test
    public  void test(){
        //1 1 2-3 3 5
        ListNode build = ListNode.build(1, 2, 3, 4, 5,6);
        build = reverseKGroup(build,2);
        System.out.println("build = " + build);
    }

    public ListNode reverseKGroup(ListNode head, int k){
        int length  = getLength(head);

        int left = 1;
        for (int i=1; i<length;i++){
            if(left+k-1>length){
                break;
            }
            head =  reverseBetween(head,left,left+k-1);
            left = left+k;
        }
       return head;

    }

    private int getLength(ListNode head) {
        if(head==null){
            return  0;
        }

        int length = 1;
        ListNode dummy = head;
        while (dummy!=null){
            dummy = dummy.next;
            if(dummy!=null){
                length ++;
            }
        }
        return length;
    }

    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || n < m) {
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;

        for(int i =1;i<m;i++){
            head = head.next;
        }
        ListNode prev = head;
        ListNode mNode = prev.next;
        ListNode nNode = mNode;
        ListNode postNode = nNode.next;

        for(int i = m;i<n;i++){
            ListNode next = postNode.next;
            postNode.next = nNode;
            nNode  = postNode;
            postNode = next;
        }
        prev.next = nNode;
        mNode.next = postNode;
        return dummy.next;
    }

}
